import {
	ref,
	reactive
} from 'vue';

export function useWebSocket() {
	const state = reactive({
		data: null,
		isCreate: false, // WebSocket 是否创建成功
		isConnect: false, // 是否已经连接
		isInitiative: false, // 是否主动断开
		timeoutNumber: 60, // 心跳检测间隔
		heartbeatTimer: null, // 心跳检测定时器
		reconnectTimer: null, // 断线重连定时器
		socketExamples: null, // WebSocket 实例
		againTime: 3, // 重连等待时间(单位秒)
	});



	// 初始化 WebSocket 连接
	const initSocket = (url) => {
		console.log('初始化 WebSocket');
		state.socketExamples = uni.connectSocket({
			url: url,
			header: {
				'content-type': 'application/json',
			},
			success: (res) => {
				state.isCreate = true;
				console.log('WebSocket 创建成功', res);
				// createSocket();
			},
			fail: (rej) => {
				console.error('WebSocket 创建失败', rej);
				state.isCreate = false;
			},
		});
	
		createSocket();
	};

	// 创建 WebSocket 连接
	const createSocket = () => {
		
		
			try {
				state.socketExamples.onOpen(() => {
					console.log('WebSocket 连接成功');
					state.isConnect = true;
					clearInterval(state.heartbeatTimer);
					clearTimeout(state.reconnectTimer);
					// 打开心跳检测
					heartbeatCheck();
				});

				// 监听 WebSocket 接受到服务器的消息事件
				state.socketExamples.onMessage((res) => {
					console.log('收到消息', res);
				
					try {
						// Trim any unwanted spaces
						const trimmedRes = res.data.trim();
						const parsedRes = JSON.parse(trimmedRes);

						uni.$emit('WS', parsedRes);
					} catch (e) {
						console.error('解析 JSON 失败:', e);
					}
				});

				// 监听 WebSocket 连接关闭事件
				state.socketExamples.onClose(() => {
					console.log('WebSocket 关闭了');
					state.isConnect = false;
					reconnect();
				});

				// 监听 WebSocket 错误事件
				state.socketExamples.onError((res) => {
					console.log('WebSocket 出错了', res);
					state.isInitiative = false;
				});
			} catch (error) {
				console.warn('WebSocket 初始化失败', error);
			}
		
	};

	// 发送消息
	const sendMsg = (value) => {

		const param = JSON.stringify(value);
		return new Promise((resolve, reject) => {
			state.socketExamples.send({
				data: param,
				success(res) {
					console.log('消息发送成功', res);
					resolve({ status: 'success', data: res }); // Resolve with success status
				},
				fail(error) {
					console.log('消息发送失败', error);
					reject({ status: 'fail', error: error }); // Reject with fail status
				},
			});
		});
	};

	// 开启心跳检测
	const heartbeatCheck = () => {
		console.log('开启心跳');
		state.data = {
			state: 1,
			method: 'heartbeat',
		};
		state.heartbeatTimer = setInterval(() => {
			// sendMsg(state.data);
		}, state.timeoutNumber * 1000);
	};
	// 重连次数限制
	let reconnectAttempts = 0;
	const maxReconnectAttempts = 10;

	// 重新连接
	const reconnect = () => {
		// 停止发送心跳
		clearTimeout(state.reconnectTimer);
		clearInterval(state.heartbeatTimer);
		// 如果不是人为关闭的话，进行重连
		if (!state.isInitiative) {
			// 如果已重连 10 次还失败，不再重连
			if (reconnectAttempts >= maxReconnectAttempts) {
				console.log("重连次数超过最大限制，停止重连");
				return; // 停止重连
			}

			reconnectAttempts++; // 增加重连次数

			state.reconnectTimer = setTimeout(() => {
				initSocket(); // 尝试重新连接
			}, state.againTime * 1500);

		}
	};

	// 关闭 WebSocket 连接
	const closeSocket = (reason = '关闭') => {
		state.socketExamples.close({
			reason,
			success() {
				state.data = null;
				state.isCreate = false;
				state.isConnect = false;
				state.isInitiative = true;
				state.socketExamples = null;
				clearInterval(state.heartbeatTimer);
				clearTimeout(state.reconnectTimer);
				console.log('关闭 WebSocket 成功');
			},
			fail() {
				console.log('关闭 WebSocket 失败');
			},
		});
	};

	return {
		state,
		initSocket,
		sendMsg,
		closeSocket,
	};
}